package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"proj-mgmt-tools/cache"
	"proj-mgmt-tools/models"
	"proj-mgmt-tools/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "没有找到该用户",
		})
		return
	}

	if user.Password != pkg.Md5Str(password) {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码不正确",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}

func BookAdd(c *gin.Context) {
	title := c.PostForm("title")
	addr := c.PostForm("addr")
	content := c.PostForm("content")

	if title == "" || addr == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}

	data := models.Book{

		Title:   title,
		Addr:    addr,
		Content: content,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	redis_key := "book_add_" + strconv.Itoa(int(data.ID))
	var book models.Book
	models.DB.Where("id = ?", book.ID).Debug().First(&book)
	jsonData, _ := json.Marshal(book)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}

func BookList(c *gin.Context) {
	var book []models.Book

	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&book)
		jsonData, _ := json.Marshal(book)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &book)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": book,
	})
}

func Detail(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	var book models.Book
	err := models.DB.Where("id = ?", id).First(&book).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不存在",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "详情展示成功",
		"data": book,
	})
	return
}

func BookDel(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	var book models.Book

	err := models.DB.Where("id = ?", id).Delete(&book).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "book_del" + strconv.Itoa(int(id))
	cache.Rdb.Del(cache.Ctx, redis_key)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
